class Composite < ActiveRecord::Base
  
  attr_accessible :name, :title, :version, :path, :description
  
  validates :name,  :presence => true
  validates :path,  :presence => true
  
  def self.collect_composite(composite_soa)
    composite = Composite.where(name: composite_soa.name, path: composite_soa.path).first
    if composite.nil?
      composite = Composite.new
      composite.name = composite_soa.name
      composite.path = composite_soa.path
      composite.version = composite_soa.version.to_s
      fill_fields(composite)
    end
    composite.save if composite.new_record? or composite.changed?
    composite
  end
  
  def self.fill_fields(composite)
    if composite.description.nil? or composite.description.length == 0
      ref = Composite.find(:all, :conditions => "name = '#{composite.name}' and description <> ''").first
      composite.description = ref.description if !ref.nil?
    end
    if composite.title.nil? or composite.title.length == 0
      ref = Composite.find(:all, :conditions => "name = '#{composite.name}' and title <> ''").first
      composite.title = ref.title if !ref.nil?
    end
  end
  
  def self.composites_by_name(name)
    Composite.where(:name => name)
  end
  
end
